package com.team7.happycommunity.gatway.utils;

import com.auth0.jwt.JWTSigner;
import com.auth0.jwt.JWTVerifier;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class JWTUtils {

    @Value("${my.jwt.secret}")
    private String secret;
    @Value("${my.jwt.exp}")
    private String exp ;
    @Value("${my.jwt.payload}")
    private String payload;
    //加密，传入一个对象和有效期
    public <T> String sign(T object, long maxAge) {
        try {
            final JWTSigner signer = new JWTSigner(secret);
            final Map<String, Object> claims = new HashMap<String, Object>();
            ObjectMapper mapper = new ObjectMapper();
            String jsonString = mapper.writeValueAsString(object);
            claims.put(payload, jsonString);
            claims.put(exp, System.currentTimeMillis() + maxAge);
            return signer.sign(claims);
        } catch (Exception e) {
            return null;
        }
    }

    //解密，传入一个加密后的token字符串和解密后的类型
    public <T> T unsign(String jwt, Class<T> classT) {
        final JWTVerifier verifier = new JWTVerifier(secret);
        try {
            final Map<String,Object> claims= verifier.verify(jwt);
            if (claims.containsKey(exp) && claims.containsKey(payload)) {
                long exp_ = (Long)claims.get( exp);
                long currentTimeMillis = System.currentTimeMillis();
                if (exp_ > currentTimeMillis) {
                    String json = (String)claims.get(payload);
                    ObjectMapper objectMapper = new ObjectMapper();
                    return objectMapper.readValue(json, classT);
                }
            }
            return null;
        } catch (Exception e) {
            return null;
        }

    }
}
